<template>
  <section>
    <div id="myChart" :style="{width: '100%', height: '600px'}"></div>
    <el-button @click="Link">websocket</el-button>
  </section>
</template>

<script>

// 引入基本模板
let echarts = require('echarts/lib/echarts')
// 引入柱状图组件
require('echarts/lib/chart/bar')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
// require('echarts-wordcloud');

export default {
  name: "delete",

  data() {
    return {
      msg: 'Welcome to Your Vue.js App',
      path: "ws://localhost:3000/ws",
      socket: "",
      echartsDataKey: [],
      echartsDataValue: [],
      value: [10,20,30,40,50,60]
    }
  },
  beforeMount() {
    // this.getEchartsData()
  },

  created() {
    this.init()
  },
  mounted() {
    this.drawLine();
    // 初始化
  },

  methods: {
    async getEchartsData() {
      var ret = await this.$axios.get('http://127.0.0.1/sales/echarts/');
      console.log(ret)
      debugger
      this.echartsDataKey = Object.keys(ret.data)
      this.echartsDataValue = Object.values(ret.data)
      // debugger
      for (var i = 0; i < this.echartsDataValue.length; i++) {
        this.value.push(this.echartsDataValue[i])
      }
    },

    drawLine() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(document.getElementById('myChart'))
      // 绘制图表
      myChart.setOption({
        title: {text: '在Vue中使用echarts'},
        tooltip: {},
        xAxis: {
          data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          // data: [5, 20, 36, 10, 10, 20]
          data: this.value
        }]
      });
    },

    init() {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },

    open: function () {
      console.log("socket连接成功")
    },
    error: function () {
      console.log("连接错误")
    },
    getMessage: function (msg) {
      console.log(JSON.parse(msg.data))
      this.value = Object.values(JSON.parse(msg.data))
      console.log(this.value)
      this.drawLine()
      // this.$message("新消息提示...")
    },
    send: function () {
      this.socket.send("hello world")
    },
    close: function () {
      console.log("socket已经关闭")
    },

    Link() {
      this.send()
    }
  }
}
</script>

<style scoped>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

/*设置地图的宽高*/
#allmap {
  height: 500px;
  overflow: hidden;
}

</style>